package com.code.netty;

import java.time.LocalDateTime;
import java.util.ArrayList;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.GlobalEventExecutor;
import java.util.List;
/**
 * 聊天的ehandler
 * TextWebSocketFrame  用于为websockt处理文本的对象
 * @author asus
 *
 */
public class ChatHandler extends SimpleChannelInboundHandler<TextWebSocketFrame>{

    //用于记录和管理所有客户端的channel
    private static ChannelGroup clients =
            new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    private static List<ChannelId> list=new ArrayList<>();
    @Override
    protected void messageReceived(ChannelHandlerContext ctx, TextWebSocketFrame msg)
            throws Exception {
        //客户端传递过来的消息
        String content = msg.text();
        System.out.println(clients+"     "+ctx.channel());
        System.out.println("接收到了客户端的消息是:" + content);
        ChannelId channelId=ctx.channel().id();
        for (Channel channel : clients){
            if (channel.id() != channelId){
                channel.writeAndFlush(new TextWebSocketFrame(msg.text()));
            }
        }
    }

    //客户端创建的时候触发，当客户端连接上服务端之后，就可以获取该channel，然后放到channelGroup中进行统一管理
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        clients.add(ctx.channel());
        list.add(ctx.channel().id());
        System.out.println("用户"+ctx.name()+"上线");
    }

    //客户端销毁的时候触发，
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        //当handlerRemoved 被触发时候，channelGroup会自动移除对应的channel
        //clients.remove(ctx.channel());
        System.out.println("客户端断开，当前被移除的channel的短ID是：" +ctx.channel().id().asShortText());
    }
}
